import { AxiosRequestConfig } from "axios";
import AxiosRequest from "../axiosRequest";
import { ReturnPlugin, YFWRequestOptions } from "../types";
import {throttle, type ThrottleSettings} from "lodash-es";

export function ThrottlePlugin(
  requestIns: AxiosRequest,
  options: YFWRequestOptions
): ReturnPlugin {
  const {throttleWait, throttleLeading, throttleTrailing } = options

  if (!throttleWait) {
    return {};
  }

  let throttleFn = requestIns.pluginStore.throttleFn;
  if (!throttleFn) {
    const options: ThrottleSettings = {};
    if (throttleLeading) {
      options.leading = throttleLeading;
    }
    if (throttleTrailing) {
      options.trailing = throttleTrailing;
    }
    const originRequest = requestIns.request.bind(requestIns);
    const thottleFn = throttle(
      (callback: any) => callback(),
      throttleWait,
      options
    );
    requestIns.request = (params: AxiosRequestConfig) => {
      return new Promise((resolve, reject) => {
        thottleFn(() => {
          originRequest(params)
            .then((res) => resolve(res as any))
            .catch(reject);
        });
      });
    };
  }
  return {}
}
